package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.SellerMapper;
import com.itheima.travel.pojo.Seller;
import com.itheima.travel.pojo.SellerExample;
import com.itheima.travel.req.SellerVo;
import com.itheima.travel.service.SellerService;
import com.itheima.travel.session.SubjectSeller;
import com.itheima.travel.session.SubjectSellerContext;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @author YYP
 * @date 2020/11/13
 */
@Service
public class SellerServiceImpl implements SellerService {
    @Autowired
    public SellerMapper sellerMapper;
    @Autowired
    public SubjectSellerContext subjectSellerContext;
    /**
     * 卖家注册
     * @param sellerVo
     * @return
     */
    @Override
    public Boolean registerSeller(SellerVo sellerVo) {
        //对象转换vo->pojo
        //BeanConv,底层依赖BeanUtils
        Seller seller = BeanConv.toBean(sellerVo, Seller.class);
        //加密
        seller.setPassword(MD5Coder.md5Encode(sellerVo.getPassword()));
        System.out.println("service：转完后的对象"+seller);
        //调用dao完成注册
        int i = sellerMapper.insert(seller);
        return i>0;
    }

    /**
     * 卖家登陆
     * @param sellerVo
     * @return
     */
    @Override
    public SellerVo loginSeller(SellerVo sellerVo) {
        //拼接查询条件
        SellerExample example = new SellerExample();
        example.createCriteria()
                .andUsernameEqualTo(sellerVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(sellerVo.getPassword()));

        List<Seller> sellerList = sellerMapper.selectByExample(example);
        if (sellerList.size() > 0) {
            //pojo:与数据库表以一对应的
            Seller seller = sellerList.get(0);
            //vo:与web层的业务一一对应
            SellerVo resultSellerVo = BeanConv.toBean(seller, SellerVo.class);
            //---------------------
            //登陆成功后将登陆成功的卖家信息保存到session中
            //此对象为session封装数据时使用到的对象
            //session中用于存放数据的对象
            SubjectSeller subjectSeller = BeanConv.toBean(resultSellerVo, SubjectSeller.class);
            //生成存放到session中对象的key
            String accessToken = UUID.randomUUID().toString();
            //将token存放到响应结果中（为的是下一次请求时携带token，这样才能从session中获取对应的数据信息）
            resultSellerVo.setToken(accessToken);
            subjectSeller.setToken(accessToken);

            //将登陆信息保存到session中
            subjectSellerContext.createdSubject(accessToken,subjectSeller);
            //-------------------------
            return resultSellerVo;

        }

        return null;
    }

    @Override
    public void loginOutSeller() {
        subjectSellerContext.deleteSubject();
    }

    @Override
    public Boolean isLogin() {
        return subjectSellerContext.existSubject();
    }
}
